#include <scdl/parser/Symbol.hpp>
#include <scdl/parser/internal.hpp>

#include <cstdlib>
#include <cstring>

using namespace scdl;

SymbolList::SymbolList()
        : size(0), capacity(4)
{
        elements = new Symbol*[capacity];
}

SymbolList::~SymbolList()
{
        for (int i = 0; i < size; i++) {
                elements[i]->unref();
        }
        delete[] elements;
}

void SymbolList::pushElement(Symbol *sym)
{
        if (size == capacity) {
                int old_capacity = capacity;
                capacity += capacity;
                Symbol **newarray = new Symbol*[capacity];
                memcpy(newarray, elements, sizeof(Symbol *) * old_capacity);
                delete[] elements;
                elements = newarray;
        }

        elements[size] = sym;
        sym->ref();
        size ++;
}

void SymbolList::updateElement(int idx, Symbol *sym)
{
        Symbol **slot = elements + idx;
        if (*slot == sym)
                return;

        (*slot)->unref();
        *slot = sym;
        sym->ref();
}

int SymbolList::getNrElements()
{
        return size;
}

Symbol *SymbolList::getElement(int idx)
{
        if (idx < 0 || idx >= size)
                return 0;
        return elements[idx];
}

